const express = require('express');
const db = require('../db');
const md5=require('../util/md5')
//导入判断目录是否已经存在的处理模块
const mkdir = require('../util/mkdirs')
//引入中间件
const multer = require('multer');
var fs = require('fs');
  const path = require('path'); // 导入 path 模块
const router = express.Router();
//使用multer解析FormData数据
const storage = multer.memoryStorage(); // 将文件存储在内存中
const upload = multer({ storage: storage });
//登录验证jwt包
const jwt = require("jsonwebtoken");
//简易随机生成
const secretKey = 'weiyinglin';
const moment = require('moment');
const schedule = require('node-schedule');
const io = require("socket.io-client")
const socket = io();

//插入消息的数据库接口
router.post('/sendMessage',(req,res)=>{
   const {senderId,receiverId,content,content_type,sendTime}=req.body
   const insertQuery='INSERT INTO messages (sender_id,receiver_id,content,content_type,send_time) VALUES(?,?,?,?,?) '
   db.query(insertQuery,[senderId,receiverId,content,content_type,sendTime],(err,rows)=>{
    if (err) {
        console.error('Error inserting user to database', err);
        return res.status(500).json({ message: '服务器错误' });
      } 
      return res.status(201).json({message:'消息存入成功'})
   })


})

//根据appointment_id查询对应咨询师的信息
router.get('/getConsultantInfoByAppointment_id',(req,res)=>{
    const {appointment_id}=req.query
    const selectQuery='SELECT * FROM consultants WHERE id=(SELECT counselor_id FROM appointments WHERE appointment_id=? )'
    db.query(selectQuery,[appointment_id],(err,rows)=>{
        if (err) {
            console.error('Error inserting user to database', err);
            return res.status(500).json({ message: '服务器错误' });
          } 
        return res.status(201).json(rows[0])

    })
})

//根据appointment_id查询对应用户id
router.get('/getuserIdByappointment_id',(req,res)=>{
    const {appointment_id}=req.query
    const selectQuery='SELECT user_id FROM appointments WHERE appointment_id=?'
    db.query(selectQuery,[appointment_id],(err,rows)=>{
        if (err) {
            console.error('Error inserting user to database', err);
            return res.status(500).json({ message: '服务器错误' });
          } 
        return res.status(201).json(rows[0])

    })
})

module.exports=router